<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1080">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="140px"
      v-loading="formLoading"
      :disabled="disabled"
    >
      <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
        <el-tab-pane label="基础信息" name="item">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="物料名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="物料分类" prop="materialCategoryId">
                <el-select
                  v-model="formData.materialCategoryId"
                  clearable
                  filterable
                  placeholder="请选择"
                  class="!w-1/1"
                >
                  <el-option
                    v-for="item in supplierList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="物料来源" prop="materialSource">
                <el-input v-model="formData.materialSource" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="规格" prop="specification">
                <el-input v-model="formData.specification" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="型号" prop="model">
                <el-input v-model="formData.model" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="类别" prop="category">
                <el-input v-model="formData.category" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="颜色" prop="color">
                <el-input v-model="formData.color" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="物料等级" prop="materialGrade">
                <el-input v-model="formData.materialGrade" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="物料条形码" prop="barcode">
                <el-input v-model="formData.barcode" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="附件" prop="attachment">
                <UploadFile :is-show-tip="false" v-model="formData.attachment" :limit="1" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="生产日期" prop="productionDate">
                <el-date-picker
                  v-model="formData.productionDate"
                  type="date"
                  value-format="x"
                  placeholder="请选择"
                  class="!w-1/1"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="品牌" prop="brand">
                <el-input v-model="formData.brand" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="重量" prop="weight">
                <el-input v-model="formData.weight" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="图号" prop="drawingNumber">
                <el-input v-model="formData.drawingNumber" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="材质" prop="materialQuality">
                <el-input v-model="formData.materialQuality" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="特性" prop="characteristics">
                <el-input v-model="formData.characteristics" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="螺纹" prop="thread">
                <el-input v-model="formData.thread" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="OEM厂商1" prop="oem1">
                <el-input v-model="formData.oem1" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="OEM厂商2" prop="oem2">
                <el-input v-model="formData.oem1" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="OEM厂商3" prop="oem3">
                <el-input v-model="formData.oem1" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="测试字段001" prop="test001">
                <el-input v-model="formData.test001" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户型号" prop="customerModel">
                <el-input v-model="formData.customerModel" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="版本" prop="version">
                <el-input v-model="formData.version" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="采购员" prop="purchaserId">
                <el-select
                  v-model="formData.purchaserId"
                  clearable
                  filterable
                  placeholder="请选择"
                  class="!w-1/1"
                >
                  <el-option
                    v-for="item in supplierList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="库位" prop="warehouseLocationId">
                <el-select
                  v-model="formData.warehouseLocationId"
                  clearable
                  filterable
                  placeholder="请选择"
                  class="!w-1/1"
                >
                  <el-option
                    v-for="item in supplierList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="仓库区域" prop="warehouseAreaId">
                <el-select
                  v-model="formData.warehouseAreaId"
                  clearable
                  filterable
                  placeholder="请选择"
                  class="!w-1/1"
                >
                  <el-option
                    v-for="item in supplierList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="备注" prop="remarks">
                <el-input
                  type="textarea"
                  v-model="formData.remarks"
                  maxlength="100"
                  show-word-limit
                  placeholder="请输入备注"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
      <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
        <el-tab-pane label="图片信息" name="item">
          <el-row :gutter="20">
           
              <el-form-item label="物料图片" prop="photoUrl">
               <el-upload
    v-model:file-list="fileList"
    action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
    list-type="picture-card"
    :on-preview="handlePictureCardPreview"
    :on-remove="handleRemove"
  >
    <el-icon><Plus /></el-icon>
  </el-upload>
              </el-form-item>
          </el-row>
        </el-tab-pane>
      </el-tabs>
      <!-- 
      <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
        <el-tab-pane label="费用及付款" name="item">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="整单折扣额" prop="orderDiscountAmount">
                <el-input v-model="formData.orderDiscountAmount" style="max-width: 600px">
                  <template #append>分摊</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="整单折扣率" prop="orderDiscountRate">
                <el-input v-model="formData.orderDiscountRate" style="max-width: 600px">
                  <template #append>%</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="成交金额" prop="transactionAmount">
                <el-input v-model="formData.transactionAmount" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发票类型" prop="invoiceType">
                <el-input disabled v-model="formData.invoiceType" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="税率" prop="taxRate">
                <el-input disabled v-model="formData.taxRate" style="max-width: 600px">
                  <template #append>%</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="支付方式" prop="paymentMethod">
                <el-select
                  v-model="formData.paymentMethod"
                  clearable
                  filterable
                  placeholder="请选择"
                  class="!w-1/1"
                >
                  <el-option
                    v-for="item in supplierList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="抵扣预付款" prop="advancePaymentDeduction">
                <el-input
                  disabled
                  v-model="formData.advancePaymentDeduction"
                  style="width: 88px; margin-right: 10px"
                />
                <el-button type="primary" @click="preOrder" style="width: 85px"
                  >选择预付款</el-button
                >
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="采购费用" prop="purchaseFee">
                <el-input
                  disabled
                  v-model="formData.purchaseFee"
                  style="width: 84px; margin-right: 10px"
                />
                <el-button type="primary" @click="feeDetailForm" style="width: 40px"
                  >编辑</el-button
                >
                <el-button type="primary" @click="allocation" style="width: 40px">分摊</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs> -->
    </el-form>
    <!-- 子表的表单 -->
    <!-- <ContentWrap>
      <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
        <el-tab-pane label="物料列表" name="item">
          <StockList ref="itemFormRef" :items="formData.items" :disabled="disabled" />
        </el-tab-pane>
      </el-tabs>
    </ContentWrap> -->
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading" v-if="!disabled">
        确 定
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <Advance ref="preFormRef" :items="formData.items" :disabled="disabled" />
  <FeeDetail ref="feeDetailRef" :items="formData.items" :disabled="disabled" />
</template>
<script setup lang="ts">
import { StockInApi, StockInVO } from '@/api/erp/stock/in'
import Advance from './components/Advance.vue'
import FeeDetail from './components/FeeDetail.vue'
import { SupplierApi, SupplierVO } from '@/api/erp/purchase/supplier'
import StockList from './components/StockList.vue'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { ElMessage } from 'element-plus'
/** ERP 其它入库单 表单 */
defineOptions({ name: 'StockInForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改；detail - 详情
const formData = ref({
  id: undefined,
  name: undefined,
  materialCategoryId: undefined,
  materialSource: undefined,
  specification: undefined,
  model: undefined,
  category: undefined,
  color: undefined,
  materialGrade: undefined,
  barcode: undefined,
  attachment: undefined,
  productionDate: undefined,
  brand: undefined,
  weight: undefined,
  drawingNumber: undefined,
  materialQuality: undefined,
  characteristics: undefined,
  thread: undefined,
  oem1: undefined,
  oem2: undefined,
  oem3: undefined,
  test001: undefined,
  customerModel: undefined,
  version: undefined,
  purchaserId: undefined,
  warehouseLocationId: undefined,
  warehouseAreaId: undefined,
  remarks: undefined
})
const fileList = ref<UploadUserFile[]>([
  {
    name: 'food.jpeg',
    url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
  },
  {
    name: 'plant-1.png',
    url: '/images/plant-1.png',
  },
  {
    name: 'food.jpeg',
    url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
  },
  {
    name: 'plant-2.png',
    url: '/images/plant-2.png',
  },
  {
    name: 'food.jpeg',
    url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
  },
  {
    name: 'figure-1.png',
    url: '/images/figure-1.png',
  },
  {
    name: 'food.jpeg',
    url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
  },
  {
    name: 'figure-2.png',
    url: '/images/figure-2.png',
  },
])
const dialogImageUrl = ref('')

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
const formRules = reactive({
  name: [{ required: true, message: '物料名称不能为空', trigger: 'blur' }],
  materialCategoryId: [{ required: true, message: '物料分类不能为空', trigger: 'blur' }],
  materialSource: [{ required: true, message: '物料来源不能为空', trigger: 'blur' }],
  specification: [{ required: true, message: '规格不能为空', trigger: 'blur' }],
  model: [{ required: true, message: '型号不能为空', trigger: 'blur' }],
  category: [{ required: true, message: '类别不能为空', trigger: 'blur' }],
  color: [{ required: true, message: '颜色不能为空', trigger: 'blur' }],
  materialGrade: [{ required: true, message: '物料等级不能为空', trigger: 'blur' }],
  version: [{ required: true, message: '版本不能为空', trigger: 'blur' }],
  purchaserId: [{ required: true, message: '采购员不能为空', trigger: 'blur' }],
  warehouseLocationId: [{ required: true, message: '库位不能为空', trigger: 'blur' }],
  warehouseAreaId: [{ required: true, message: '仓库区域不能为空', trigger: 'blur' }]
})
const disabled = computed(() => formType.value === 'detail')
const formRef = ref() // 表单 Ref
const supplierList = ref<SupplierVO[]>([]) // 供应商列表
const feeDetailRef = ref()
const feeDetailForm = () => {
  feeDetailRef.value.open()
}
const preFormRef = ref()

const preOrder = () => {
  preFormRef.value.open()
}
const allocation = () => {
  ElMessage({
    message: '分摊成功',
    type: 'success',
    plain: true
  })
}
/** 子表的表单 */
const subTabsName = ref('item')
const itemFormRef = ref()

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await StockInApi.getStockIn(id)
    } finally {
      formLoading.value = false
    }
  }
  // 加载供应商列表
  supplierList.value = await SupplierApi.getSupplierSimpleList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  await itemFormRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as StockInVO
    if (formType.value === 'create') {
      await StockInApi.createStockIn(data)
      message.success(t('common.createSuccess'))
    } else {
      await StockInApi.updateStockIn(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    supplierId: undefined,
    settlementDate: undefined,
    remark: undefined,
    items: [],
    entryOrderNumber: undefined,
    relatedPurchaseOrder: undefined,
    settlementPeriod: undefined,
    project: undefined,
    projectPhase: undefined,
    documentDate: undefined,
    createdBy: undefined,
    department: undefined,
    operator: undefined,
    deliveryOrderNumber: undefined,
    purchaseRemark: undefined,
    amountExcludingTax: undefined,
    amountIncludingTax: undefined,
    customerOrderNumber: undefined,
    discountAmount: undefined,
    discountRate: undefined,
    transactionAmount: undefined,
    invoiceType: undefined,
    taxRate: undefined,
    paymentMethod: undefined,
    deductAdvancePayment: undefined,
    purchaseFee: undefined
  }
  formRef.value?.resetFields()
}
</script>
